//
//  DiseaseViewController.m
//  TestARC
//
//  Created by 晓泉 吴 on 12-9-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DiseaseViewController.h"
#import "DiseaseDetailViewController.h"
#import "MyExtensions.h"
#import "JSON/SBJson.h"
#import "DiseaseSymtomViewController.h"
#import "DiseaseDrugViewController.h"
#import "BlueButton.h"

#define CommonViewTAG 100
#define SeggestionViewTAG 101

@interface DiseaseViewController ()

@end

@implementation DiseaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (showOverlayView) {
        [self.navigationController setNavigationBarHidden:TRUE animated:YES];
    } else {
        [self.navigationController setNavigationBarHidden:FALSE animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    
    [self.navigationController setNavigationBarHidden:FALSE animated:YES];
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.navigationItem.title=@"疾病";
    self.searchBar.placeholder = @"搜索疾病";
    self.hipLabel.text = [NSString stringWithFormat:@"常见疾病"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)loadCommonData
{
    [self.commonArray removeAllObjects];
    FMResultSet *rs =[self.dbHelper quaryCommonDisease];
    while ([rs next]) {
        [self.commonArray addObject:[rs resultDictionary]];
    }
}

-(void)loadSeggestionData:(NSString *)queryText
{
    [self.seggestionArray removeAllObjects];
    FMResultSet *rs =[self.dbHelper searchDiseaseSeggestion:queryText];
    //NSLog(@"rs.query=%@",rs.query);
    while ([rs next]) {
        [self.seggestionArray addObject:[rs resultDictionary]];
    }
    
}

-(void)setCellImage:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.imageView.image = [UIImage imageNamed:@"table_disease_logo_23.png"];
}

//-----------------选择列表项---------------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    //NSLog(@"选择了 %d 行",row);
    NSDictionary *disease;
    if (tableView.tag == CommonViewTAG) {
        disease = [self.commonArray objectAtIndex:row];
        
    } else {
        disease = [self.seggestionArray objectAtIndex:row];
    }
    
    [self loadDiseaseDetailData:disease];
        
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void) loadDiseaseDetailData:(NSDictionary *)detail
{
    [self showWaitView:nil];
    
    //NSLog(@"disease=%@",detail);
    NSString *queryid = [detail objectForKey:@"queryid"];
    NSString *flag = @"B90";
    int timestamp = (int)[[NSDate date]timeIntervalSince1970];
    NSString * checksum = [[NSString stringWithFormat:@"%d%@%d%@%dyaoxia",timestamp,flag,timestamp,queryid,timestamp]md5];
    NSString *URL_DETAIL = [NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet?style=ae062a0f29297c33f8ab85b1d4b7741f&flag=%@&key=%@&timestamp=%d&checksum=%@",flag,queryid,timestamp,checksum];
    NSLog(@"URL_DETAIL=%@",URL_DETAIL);
    NSURL *url = [NSURL URLWithString:URL_DETAIL];
    request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        [self hideWaitView];
        
        // Use when fetching text data
        NSString *responseString = [request responseString];
        
        //NSLog(@"responseString = %@",responseString);
        id json = [responseString JSONValue];
        //NSLog(@"meg = %@",[json objectForKey:@"drugInfo"]);
        if ([[json objectForKey:@"code"]intValue] == 500) {
            NSLog(@"%@",[json objectForKey:@"message"]);
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"网络加载错误"
                                  message:[NSString stringWithFormat:@"%@",[json objectForKey:@"message"]]
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            return ;
        }
        
        [self showDiseaseDetailView:json diseaseName:[detail objectForKey:@"name"]];
        
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request setFailedBlock:^{
        [self hideWaitView];
        
        NSError *error = [request error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request startAsynchronous];
    
    

}

- (void) showDiseaseDetailView:(NSDictionary *)json diseaseName:(NSString *)name
{
    //设置标签栏
    UITabBarController *tabController = [[UITabBarController alloc] init];
    tabController.title = name;
    BlueButton *blueButton = [[BlueButton alloc] init];
    [blueButton addTarget:self action:@selector(backToMain) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *button = [[UIBarButtonItem alloc]
                               initWithCustomView:blueButton];
    tabController.navigationItem.rightBarButtonItem = button;
//    tabController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"药" style:UIBarButtonItemStylePlain target:self action:@selector(backToMain)];
    //tabController.tabBar.frame = CGRectMake(0, 64+50, 320, 70);
    //设置每个标签
    DiseaseDetailViewController *viewController1 = [[DiseaseDetailViewController alloc] initWithNibName:@"DiseaseDetailViewController" bundle:nil];
    UITabBarItem *tab1 = [[UITabBarItem alloc] initWithTitle:@"疾病简介"
                                                       image:[UIImage imageNamed:@"disease_detail_pref.png"]
                                                         tag:1];
    [viewController1 setTabBarItem:tab1];
    viewController1.url = [json objectForKey:@"briefUrl"];
    //[viewController1.view setBackgroundColor:[UIColor redColor]];
    
    
    DiseaseSymtomViewController *viewController2 = [[DiseaseSymtomViewController alloc] initWithNibName:@"DiseaseSymtomViewController" bundle:nil];
    UITabBarItem *tab2 = [[UITabBarItem alloc] initWithTitle:@"症状"
                                                       image:[UIImage imageNamed:@"disease_detail_sym.png"]
                                                         tag:2];
    [viewController2 setTabBarItem:tab2];
    viewController2.symptomArray = [json objectForKey:@"symptomArray"];
    //[viewController2.view setBackgroundColor:[UIColor greenColor]];
    
    DiseaseDrugViewController *viewController3 = [[DiseaseDrugViewController alloc] initWithNibName:@"DiseaseDrugViewController" bundle:nil];
    UITabBarItem *tab3 = [[UITabBarItem alloc] initWithTitle:@"治疗药物"
                                                       image:[UIImage imageNamed:@"disease_detail_drug.png"]
                                                         tag:3];
    [viewController3 setTabBarItem:tab3];
    //[viewController3.view setBackgroundColor:[UIColor blueColor]];
    viewController3.drugArray = [json objectForKey:@"drugArray"];
    
    
    tabController.viewControllers = [NSArray arrayWithObjects:viewController1,
                                     viewController2,
                                     viewController3,
                                     nil];
    
    [self.navigationController pushViewController:tabController animated:YES];
}

@end
